package com.zzz.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;

/*
 * @author zzr
 * @date: 2025/07/06  17:15
 * @description: 测试 HttpServletRequest 的请求参数 API
 */
@WebServlet("/servlet9")
public class servlet9 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取键值对的参数
        // 根据参数名获取单个参数值
        String username = req.getParameter("username");
        System.out.println(username);
        String userPwd = req.getParameter("userPwd");
        System.out.println(userPwd);

        // 根据参数名获取多个参数值
        String[] hobbies = req.getParameterValues("hobby");
        System.out.println(Arrays.toString(hobbies));

        // 先获取所有参数名，再分别打印
        // 法 1：
        Enumeration<String> parameterNames = req.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String pname = parameterNames.nextElement();
            // 先假设每个参数名都有多个参数值
            String[] parameterValues = req.getParameterValues(pname);
            if (parameterValues.length > 1) {
                System.out.println(pname + ":" + Arrays.toString(parameterValues));
            } else {
                System.out.println(pname + ":" + parameterValues[0]);
            }
        }
        // 法 2：返回所有参数的 map 集合 key = 参数名 value = 参数值
        Map<String, String[]> parameterMap = req.getParameterMap();
        Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
        for (Map.Entry<String, String[]> entry : entries) {
            String pname = entry.getKey();
            String[] value = entry.getValue();
            if (value.length > 1) {
                System.out.println(pname + "=" + Arrays.toString(value));
            } else {
                System.out.println(pname + "=" + value[0]);
            }
        }
    }
}
